/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.core.service.util;

import com.alibaba.common.lang.StringUtil;
import com.pingan.mobilegw.adapterservice.ResultEnum;
import com.pingan.mobilegw.core.model.GatewayResponse;
import com.pingan.mobilegw.core.model.exception.MgwException;
import com.pingan.mobilegw.core.model.response.SingleResponseBody;

/**
 * 响应工具类
 * 
 * @author jiadao
 * @version $Id: ResponseUtil.java, v 0.1 2013-4-4 下午8:16:13 jiadao Exp $
 */
public class ResponseUtil {

    /**
     * 构造成功的响应
     * 
     * @param result 结果
     * @return 网关响应
     */
    public static GatewayResponse buildSuccessResponse(Object result) {
        return buildResponse(ResultEnum.ResultSuccess.getCode(),
            ResultEnum.ResultSuccess.getMemo(), result);
    }

    /**
     * 构造错误的网关响应
     * 
     * @param resultEnum 错误枚举
     * @param memo 错误描述
     * @return 
     */
    public static GatewayResponse buildErrorResponse(ResultEnum resultEnum, String memo) {
        return buildErrorResponse(resultEnum.getCode(), memo);
    }

    /**
     * 构造错误的网关响应
     * 
     * @param e 网关异常
     * @return
     */
    public static GatewayResponse buildErrorResponse(MgwException e) {
        return ResponseUtil.buildErrorResponse(e.getResultCode(),
            StringUtil.isNotBlank(e.getErrorMsg()) ? e.getErrorMsg() : e.getResultCode().getMemo());
    }

    /**
     * 构造错误响应
     * 
     * @param resultEnum
     * @return
     */
    public static GatewayResponse buildErrorResponse(ResultEnum resultEnum) {
        return buildErrorResponse(resultEnum.getCode(), resultEnum.getMemo());
    }

    /**
     * 构造错误响应
     * 
     * @param resultStatus
     * @param memo
     * @return
     */
    public static GatewayResponse buildErrorResponse(int resultStatus, String memo) {
        return buildResponse(resultStatus, memo, null);
    }

    /**
     * 构造响应体
     * 
     * @param resultStatus
     * @param memo
     * @param result
     * @return
     */
    public static GatewayResponse buildResponse(int resultStatus, String memo, Object result) {
        GatewayResponse gatewayResponse = new GatewayResponse();
        SingleResponseBody responseBody = new SingleResponseBody();

        //增加提示文案 +by yikong
        if (resultStatus != ResultEnum.ResultSuccess.getCode()) {
            ResultEnum en = ResultEnum.getResultEnumByCode(resultStatus);
            if (null != en) {
                responseBody.setTips(en.getTips());
            }
        }
        responseBody.setMemo(memo);
        responseBody.setResultStatus(resultStatus);
        responseBody.setResult(result);
        gatewayResponse.setResponseBody(responseBody);
        return gatewayResponse;
    }

}
